package com.simple.editor.action.impl;

import com.simple.editor.ApplicationContext;
import com.simple.editor.callback.DefaultUICallbackImpl;
import com.simple.editor.converter.FileModelConverter;
import com.simple.editor.ui.FileModel;
import com.simple.editor.ui.InfoPane;
import com.simple.editor.ui.TabbedEditorPane;
import com.simple.editor.util.UIUtilities;
import com.simple.editor.vcs.VcsClient;
import com.simple.editor.vcs.VcsClientRegistry;
import com.simple.editor.vcs.VcsFile;

import java.util.Map;

/**
 * {@link DeleteEditorUIAction} handles user "Delete File" action.
 * <p/>
 * Created with IntelliJ IDEA.
 * User: vsoroka
 * Date: 07.06.13
 * Time: 9:57
 * To change this template use File | Settings | File Templates.
 */
public class DeleteEditorUIAction extends AbstracEditorUIAction {

    private final ApplicationContext ctx;
    private final InfoPane infoPane;
    private final VcsClientRegistry vcsClientRegistry;

    public DeleteEditorUIAction(final ApplicationContext ctx, final InfoPane infoPane, final VcsClientRegistry vcsClientRegistry) {
        this.ctx = ctx;
        this.infoPane = infoPane;
        this.vcsClientRegistry = vcsClientRegistry;
    }

    @Override
    public void perform(final FileModel... files) {
        if (files != null && files.length > 0) {
            final VcsClient vcsClient = vcsClientRegistry.getCurrentVcsClient();

            final Map<String, VcsFile> vcsFilesMap = FileModelConverter.convertFiles(files);

            // remove files
            vcsClient.delete(new DefaultUICallbackImpl("Remove files", infoPane) {
                @Override
                public void onComplete() {
                    UIUtilities.invoke(new Runnable() {
                        @Override
                        public void run() {
                            for (final FileModel file : files) {
                                ctx.getComponent(TabbedEditorPane.class).closeTab(file);
                                file.setChanged(false);
                            }
                            infoPane.addInfo("Files removed.");
                        }
                    });
                }

            }, vcsFilesMap.values());

            // Refresh file status
            vcsClient.refreshStatus(new RefreshActionUICallbackImpl(vcsFilesMap, infoPane, ctx, files), vcsFilesMap.values());
        }
    }
}
